package com.asoft.common.mq;

import java.util.Map;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

public class Producer
{
        static Logger logger = Logger.getLogger(Producer.class);

        private JmsTemplate template; 
        
        private Destination destination;

        // 发送消息
        public void send(final String text) throws JMSException
        {
                template.send(this.destination,new MessageCreator()
                {
                        
                        public Message createMessage(Session session)
                                throws JMSException
                        {
                                logger.info("Sending message: " + text);
                                TextMessage message = session.createTextMessage(text);
                                return message;
                        }
                });
        }
        
        // 发送map消息
        public void send(final Map map) throws JMSException
        {
                template.send(this.destination,new MessageCreator()
                {
                        public Message createMessage(Session session)
                                throws JMSException
                        {
                                logger.info("Sending map message.size() " + map.size());
                                MapMessage message = session.createMapMessage();
                                Object[] keys = map.keySet().toArray();
                                for(int i = 0; i < keys.length; i ++)
                                {
                                        message.setObject((String)keys[i],map.get(keys[i]));
                                }
                                return message;
                        }
                });
        }

        public JmsTemplate getTemplate()
        {
                return template;
        }

        public void setTemplate(JmsTemplate template)
        {
                this.template = template;
        }

        public Destination getDestination()
        {
                return destination;
        }

        public void setDestination(Destination destination)
        {
                this.destination = destination;
        }
}
